import user from "../store/user"
import {
	Toast
} from "./com"
export const makeObjReaquest = (objectName) => {
	return uniCloud.importObject(objectName)
}
// 重要的回滚
// const transaction = await db.startTransaction()
// // 其他业务逻辑...
// // 库存减一
// const reduceRes = await db.collection('goods').where({
//   _id: 'goods_id', // 商品ID
//   stock: dbCmd.gt(1) // 限制库存大于1的才允许扣除库存
// }).update({
//   stock: dbCmd.inc(-1)
// })
// if(reduceRes.updated === 0) { // 如果没成功更新库存就认为下单失败
//   await transaction.rollback()
//   return {
//     code: 1001,
//     message: '下单失败'
//   }
// }

const request = (objectName, fnName, params = {}) => {
	const token = uni.getStorageSync('token')
	uni.showLoading()
	return new Promise((resolve, reject) => {
		try {
			const api = makeObjReaquest(objectName)
			api[fnName]({
				...params,
				token: uni.getStorageSync('token')
			}).then(res => {
				console.log("最初的res", res);
				uni.hideLoading()
				const {
					code,
					data,
					message
				} = res

				if (code == 401) {
					Toast('登录失效，请重新登录')
					reject()
				}
				if (code == 200) {
					resolve(res)
					return
				}
				const msg = message || '未知错误'
				Toast(msg)
				reject(res)
			}).catch(err => {
				reject(err)
			})
		} catch (error) {
			reject(error)
		}

	})
}

export default request